import React, { Component } from 'react';
import Item from '../Item';
import PubSub from 'pubsub-js';
import './index.css';

export default class List extends Component {
  //初始化状态
  state = {
    todos: [
      {id: '001', name: '吃饭', done: true},
      {id: '002', name: '睡觉', done: true},
      {id: '003', name: '打代码', done: false},
    ]
  }

  componentDidMount() {
    this.token = PubSub.subscribe('shucheng', (msg, data) => {
      const newTodos = [data, ...this.state.todos]
      this.setState({todos: newTodos})
    })
  }

  componentWillUnmount() {
    PubSub.unsubscribe(this.token)
  }

  render() {
    const {todos} = this.state
    return (
      <ul className="todo-main">
        {
          todos.map((todo) => {
            return <Item key={todo.id} id={todo.id} name={todo.name} done={todo.done}></Item>
          })
        }
      </ul>
    )
  }
}
